package io.gitee.mingbaobaba.apijson.querycondition.query.template.support;

import lombok.Getter;

/**
 * <p>循环查询配置</p>
 */
@Getter
public final class LoopQueryConfig {

    private static final int DEFAULT_LIMIT = 2000;

    private final int startPage;
    private final int limit;
    private final long maxRetCount;

    private LoopQueryConfig(int startPage, int limit, long maxRetCount) {
        this.startPage = startPage;
        this.limit = limit;
        this.maxRetCount = maxRetCount;
    }

    public static LoopQueryConfig of(Integer limit) {
        return of(limit, null);
    }

    public static LoopQueryConfig of(Integer limit, Integer maxRetCount) {
        return builder()
                .limit(limit)
                .maxRetCount(maxRetCount)
                .build();
    }

    public static Builder builder() {
        return new Builder();
    }

    private static int normalize(Integer value, int defaultValue) {
        if (value == null || value < 1) {
            return defaultValue;
        }
        return value;
    }

    public static final class Builder {
        private int startPage = 1;
        private int limit = DEFAULT_LIMIT;
        private long maxRetCount = Long.MAX_VALUE;

        public Builder startPage(Integer startPage) {
            if (startPage != null && startPage > 0) {
                this.startPage = startPage;
            }
            return this;
        }

        public Builder limit(Integer limit) {
            this.limit = normalize(limit, DEFAULT_LIMIT);
            return this;
        }

        public Builder maxRetCount(Integer maxRetCount) {
            if (maxRetCount != null && maxRetCount > 0) {
                this.maxRetCount = maxRetCount;
            }
            return this;
        }

        public LoopQueryConfig build() {
            return new LoopQueryConfig(startPage, limit, maxRetCount);
        }
    }
}

